package app.controllers.system;

import app.Const;
import app.models.system.User;
import app.models.system.UserRole;
import com.ifonly.activerecord.DbUtils;
import com.ifonly.activerecord.Record;
import com.ifonly.activerecord.annotation.ARDao;
import com.ifonly.activerecord.sql.config.Sql;
import com.ifonly.common.ApiMessage;
import com.ifonly.mvc.ActionKey;
import com.ifonly.mvc.Controller;

import java.util.List;

/**
 * @author <a href="mailto:ifonlymaster@163.com">ifonly</a>
 * @version 1.0 2015-12-17 15:49
 * @since JDK 1.6
 */
public class UserController extends Controller {

    @ARDao
    private UserRole dao;


    @ActionKey("")
    public void index() {
        render("index");
    }

    public void dt() {
        /**
         SELECT u.id AS id, u.username AS username, u.real_name AS real_name, u.birthday AS birthday,
         t.role_names AS role_names FROM s_user u LEFT JOIN (
         SELECT user_id, IFNULL(group_concat(r.`name`), '') as role_names
         FROM s_user_role ur, s_role r
         WHERE ur.role_id = r.id AND ur.user_id = 7) AS t
         ON u.id = t.user_id
         */
        String segment = Sql.get("user.dtSegment");
        renderDataTables(segment, "WHERE");
    }

    public void item() {
        int id = getInt(0, 0);
        User user;
        if (id == 0) {
            user = new User();
        } else {
            user = User.findByPrimaryKey(User.class, id);
            dao.findRolesByUserId(id);
        }
        List<Record> records = dao.findRoleWithUserId(id);
        setAttr("userRoles", records);
        setAttr("user", user);
        render("item");
    }

    public void status() {
        int id = getInt(0, 0);
        if (id == 1) {
            renderJson(ApiMessage.failed("超级管理员账户不允许修改状态"));
            return;
        }
        int status = getInt(1, Const.Status.DISABLE);
        DbUtils.update(Sql.get("user.updateStatus"), status, id);
        renderJson(ApiMessage.success());
    }

    public void delete() {
        int id = getInt(0, 0);
        if (id == 1) {
            renderJson(ApiMessage.failed("超级管理员账户不允许删除"));
            return;
        }
        dao.deleteUserAndUserRoles(id);
        renderSuccess();
    }

    public void save() {
        User user = getModel(User.class, "user");
        String roleIds = getParam("roleIds");
        String[] ids = roleIds.split(",");
        dao.saveUserWithRoles(user, ids);
        redirect("");
    }

}
